<?php

namespace app\job\event;

use app\common\model\plus\seckill\SeckillSku as ProductSkuModel;
use app\job\model\order\Order as OrderModel;
use app\common\model\plus\seckill\Product as ProductModel;

/**
 * 订单事件管理
 */
class CancelSekillOrder
{
    // 模型
    private $model;

    // 应用id
    private $appId;

    /**
     * 执行函数
     */
    public function handle($app_id)
    {
        try {
            $this->appId = $app_id;
            $this->model = new OrderModel();
            log_write('CancelSekillOrder TASK : ' . $app_id . '__ ', 'task');
            $model = new \app\common\model\order\Order();
            $model->transaction(function () use ($model) {
                $conn = new \think\cache\driver\Redis(config('cache.stores.redis'));
                $list = $model->where(['pay_status' => 10, 'order_source' => 50, 'order_status' => 10])->with(['deliveryUser', 'product' => ['image', 'refund'], 'address', 'express', 'extractStore', 'supplier', 'advance'])->limit(0, 100)->select();
                foreach ($list as &$item) {
                    foreach ($item['product'] as $items) {
                        $sku = ProductSkuModel::detail($items['sku_source_id']);
                        $conn->watch($sku['seckill_product_sku_id'] . '_seckill_stock');
                        $conn->watch($sku['seckill_product_id'] . '_product_stock');
                        $conn->multi();
                        $product = (new ProductModel)->where('seckill_product_id', '=', $sku['seckill_product_id'])->find();
                        $productsku = (new ProductSkuModel)->where('seckill_product_sku_id', '=', $sku['seckill_product_sku_id'])->find();
                        $conn->set($sku['seckill_product_sku_id'] . '_seckill_stock', $productsku['seckill_stock'] + $items['total_num']);
                        $conn->set($sku['seckill_product_id'] . '_product_stock', $product['stock'] + $items['total_num']);
                        $tag = $conn->exec();
                        if ($tag) {
                            // 回退主库存
                            (new ProductModel)->where('seckill_product_id', '=', $sku['seckill_product_id'])->inc('stock', $items['total_num'])->update();
                            // 回退sku库存
                            (new ProductSkuModel)->where('seckill_product_sku_id', '=', $sku['seckill_product_sku_id'])->inc('seckill_stock', $items['total_num'])->update();
                        }
                    }
                    $item->save(['order_status' => 20]);
                }
//                echo count($list) . "条记录处理完毕";
                log_write('SECKILL_ORDER SUEECSESS : ' . count($list) . "条记录处理完毕", 'task');
            });
        } catch (\Throwable $e) {
            echo 'ERROR ORDER: ' . $e->getMessage() . PHP_EOL;
            log_write('SECKILL_ORDER TASK : ' . $app_id . '__ ' . $e->getMessage(), 'task');
        }
        return true;
    }

}
